package com.atguigu.springcloud.service.impl;

import com.atguigu.springcloud.dao.OrderInfoRepository;
import com.atguigu.springcloud.entities.Employee;
import com.atguigu.springcloud.entities.OrderInfo;
import com.atguigu.springcloud.enums.EnumEO;
import com.atguigu.springcloud.request.SaveOrderInfoRequest;
import com.atguigu.springcloud.service.OrderInfoService;
import com.atguigu.springcloud.utils.ModelMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by luojie on 2018/9/7.
 */
@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT";

    @Autowired
    private EntityManager entityManager;

    @Autowired
    private OrderInfoRepository orderInfoRepository;

    @Autowired
    private RestTemplate restTemplate;


    @Override
    public List<OrderInfo> findByEmployeeId(String employeeId) {
        return orderInfoRepository.findByEmployeeId(employeeId);
    }

    @Override
    public OrderInfo save(SaveOrderInfoRequest request) {
        OrderInfo orderInfo = ModelMapperUtil.getStrictModelMapper().map(request, OrderInfo.class);
        orderInfo = orderInfoRepository.save(orderInfo);
        return orderInfo;
    }

    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderInfo updateStatus(OrderInfo orderInfo, EnumEO.OrderStatus status) {
        orderInfo.setStatus(status);
        return orderInfo;
    }

    @Override
    public OrderInfo findById(String id) {
        String hql = "from OrderInfo d where d.id='" + id + "'";
        Query query = entityManager.createQuery(hql);
        List<OrderInfo> list = query.getResultList();
        if(list == null || list.size() == 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public Employee findEmployeeById(String id) {
        return restTemplate.getForObject(REST_URL_PREFIX + "/employee/get/" + id, Employee.class);
    }
}
